<template>
	<div class="archives_sourceinfo_info" :class="fileList.length > 0 ? 'noCard' : ''">
		<div>
			<Table
				:tableData="tableData"
				:tableHead="tableHead"
				:isUseSlot="false"
				:page="listQuery.page"
				:limit="listQuery.limit"
				v-loading="listLoading"
			>
				<template slot="tool" slot-scope="{ data }">
					<el-button
						style="padding:3px;"
						icon="el-icon-document"
						@click="handleEdit(data.row)"
						type="text"
						>查看</el-button
					>
				</template>
			</Table>
			<Pagination
				v-show="total > 0"
				:total="total"
				:page.sync="listQuery.page"
				:limit.sync="listQuery.limit"
				@pagination="getList"
			></Pagination>
		</div>
		<form-tem
			:info="{ title: '源信息', width: '70%', top: '5%',col:6 }"
			:formList="formList"
			@submit="submit"
			@close="closeDialog"
			ref="formDelg"
			:dialogFormVisible.sync="dialogFormVisible"
			@change="changeSource"
			:isDisabled="true"
		>
			<el-form style="margin-left:5%">
				<el-form-item label="源图片：">
					<el-upload
						action="https://jsonplaceholder.typicode.com/posts/"
						list-type="picture-card"
						:on-preview="handlePictureCardPreview"
						:on-remove="handleRemove"
						:before-upload="befUpload"
						:limit="1"
						:http-request="htpRequest"
						:auto-upload="false"
						:file-list="fileList"
						ref="uploadFile"
						:disabled="true"
						>
					</el-upload>
				</el-form-item>
			</el-form>
		</form-tem>
		<el-dialog :visible.sync="dialogVisible">
			<img width="100%" :src="dialogImageUrl" alt="">
		</el-dialog>
	</div>
	</div>
</template>

<script>
import Pagination from "@/components/Pagination"; // 分页
import formTem from "@/template/form.temp";
import Table from "@/components/Table";
import { getRadNuclide,getRadType,getAreaInfo,getDeviceManufacturer,getUsedStatus ,getRadUsedInfo,getRadUsed, getDeviceInfo } from "@/api/RCIM/RCIM-select";
import {getSourceList, getRadInfo, insertRad, updateRad} from "@/api/RCIM/RCIM-archives";
import { deleteRad } from '@/api/RCIM/RCIM-delet';
import control from "../mixins/control";
import { validateFormNumber } from "@/utils/validateForm";
import { cloneDeep } from 'lodash';
import moment from 'moment';
export default {
	components: {
		Table,
		Pagination,
		formTem
	},
	mixins: [control],
	name: "archives_sourcelinfo_info",
	data() {
		return {
			tableData: [
				{
					id: "",
					placeName: "XXXXX",
					nuclideName: "XXXX",
					sourceCode: "XXX",
					sourceUse: "XXX"
				}
			],
			tableHead: [
				{
					prop: "placeName",
					label: "场所名称",
					align: "left"
				},
				{
					prop: "nuclideName",
					label: "核素名",
					align: "left"
				},
				{
					prop: "sourceCode",
					label: "源国家编码",
					align: "left"
				},
				{
					prop: "sourceUse",
					label: "源用途",
					align: "left"
				},
				{
					prop: "operate",
					label: "操作",
					align: "center"
				}
			],
			total: 1,
			listQuery: {
				page: 1,
				limit: 10
			},
			dialogImageUrl: '',
        	dialogVisible: false,
			listLoading: false,
			dialogFormVisible: false,
			formList: [
				{
					list: [
						{
							type: "select",
							label: "场所",
							labelWidth: "180px",
							width: "50%",
							placeholder: "",
							moduleKey: "place",
							children: "option",
							options: [
							],
							query: {
								enterpriseId: this.entData.id
							},
							fetch: getAreaInfo
						},
						{
							type: "select",
							label: "用源设备",
							labelWidth: "180px",
							width: "49.8%",
							placeholder: "",
							moduleKey: "useSourceDevice",
							children: "option",
							fetchTimes: Infinity,
							options: [
							],
							query: {
								id: this.entData.id,
								type: 'enterprise',
							},
							fetch:getDeviceInfo,
							validate: function() {
								return [
									{required: false, message: '请选择用源设备', trigger: "blur"}
								]
							}
						},
						{
							type: "input",
							label: "源国家编码",
							labelWidth: "180px",
							width: "50%",
							placeholder: "",
							maxlength: "20",
							showWordLimit: true,
							moduleKey: "sourceCode",
							validate: function() {
								return [
									{required: false, message: '请输入源国家编码', trigger: "blur"}
								]
							}
						},
						{
							type: "select",
							label: "核素名称",
							labelWidth: "180px",
							width: "50%",
							placeholder: "",
							moduleKey: "nuclideName",
							children: "option",
							options: [
							],
							fetch: getRadNuclide,
							validate: function() {
								return [
									{required: false, message: '请选择核素名称', trigger: "blur"}
								]
							}
						},
						{
							type: "select",
							label: "源类别",
							labelWidth: "180px",
							width: "50%",
							placeholder: "",
							moduleKey: "sourceType",
							children: "option",
							options: [
							],
							fetch:getRadType,
							validate: function() {
								return [
									{required: false, message: '请选择源类别', trigger: "blur"}
								]
							}
						},
						{
							type: "select",
							label: "源用途",
							labelWidth: "180px",
							width: "50%",
							placeholder: "",
							moduleKey: "sourceUse",
							fetchTimes: Infinity,
							children: "option",
							options: [
							],
							// query: {
							// 	id: '',
							// },
							// fetch:getRadUsedInfo,
							validate: function() {
								return [
									{required: false, message: '请选择源用途', trigger: "blur"}
								]
							}
						},
						{
							type: "input",
							label: "出厂活度",
							labelWidth: "180px",
							width: "50%",
							placeholder: "",
							moduleKey: "factoryActivity",
							validate: function() {
								return [
									{required: false, message: '请输入出厂活度', trigger: "blur"}
								]
							}
						},
						// {
						// 	type: "select",
						// 	label: "收储状态",
						// 	labelWidth: "180px",
						// 	width: "50%",
						// 	placeholder: "",
						// 	moduleKey: "stockpileStatus",
						// 	children: "option",
						// 	options: [
						// 	],
						// 	fetch:getUsedStatus,
						// 	validate: function() {
						// 		return [
						// 			{required: false, message: '请选择收储状态', trigger: "blur"}
						// 		]
						// 	}
						// },
						{
							type: "input",
							label: "标号",
							width: "50%",
							labelWidth: "180px",
							placeholder: "",
							moduleKey: "grade",
							validate: function() {
								return [
									{required: false, message: '请输入标号', trigger: "blur"}
								]
							}
						},
						{
							type: "date-picker",
							label: "出厂日期",
							width: "50%",
							labelWidth: "180px",
							placeholder: "",
							typeProp:"date",
							moduleKey: "factoryTime",
							validate: function() {
								return [
									{required: false, message: '请选择出厂日期', trigger: "blur"}
								]
							}
						},
						{
							type: "input",
							label: "净重",
							width: "50%",
							labelWidth: "180px",
							placeholder: "",
							moduleKey: "weight",
							validate: function() {
								return [
									{ validator: validateFormNumber, trigger: "blur" }
								]
							}
						},
						{
							type: "input",
							label: "毛重",
							width: "50%",
							labelWidth: "180px",
							placeholder: "",
							moduleKey: "hairWeight",
							validate: function() {
								return [
									{ validator: validateFormNumber, trigger: "blur" }
								]
							}
						},
						{
							type: "input",
							label: "半衰期",
							width: "50%",
							labelWidth: "180px",
							placeholder: "",
							moduleKey: "halfTime",
							validate: function() {
								return [
									{required: false, message: '请输入半衰期', trigger: "blur"}
								]
							}
						},
						{
							type: "input",
							label: "强度",
							width: "50%",
							labelWidth: "180px",
							placeholder: "",
							moduleKey: "strength"
						},
						{
							type: "date-picker",
							label: "接收日期",
							width: "50%",
							typeProp:"date",
							labelWidth: "180px",
							placeholder: "",
							moduleKey: "receiptDate"
						},
						{
							type: "select",
							label: "产源单位",
							labelWidth: "180px",
							width: "50%",
							placeholder: "",
							moduleKey: "sourceUnit",
							children: "option",
							options: [],
							fetch:getDeviceManufacturer,
							// validate: function() {
							// 	return [
							// 		{required: false, message: '请选择产源单位', trigger: "blur"}
							// 	]
							// }
						},
						{
							width:"50%"
						},
						{
							type: "switch",
							label: "是否为风险源",
							width: "100%",
							labelWidth: "180px",
							placeholder: "",
							moduleKey: "isRiskSource",
							defaultValue: 0,
							activeValue: 1,
    						inactiveValue: 0
						}
					]
				}
			],
			search: "",
			fileUpload: null,
			fileList: [],
			isRemove: false,
		};
	},
	mounted() {
		this.listQuery.id = this.entData.id
		this.getList()
	},
	methods: {
		/**
		 * @desc 加载图片回调
		 * @param {Object} params 文件信息
		 */
		async htpRequest(params){
			console.log('arguments',arguments)
			this.fileUpload = this.loadFile(params.file)
		},
		/**
		 * @desc 加载图片
		 * @param {Object} file 文件信息
		 */
		loadFile(file){
			return new Promise((res, rej) => {
				const fileRead = new FileReader()
				fileRead.readAsDataURL(file)
				fileRead.onload = function(){
					res(this.result)
				}
				fileRead.onerror = function(){
					rej('读取失败')
				}
			})
		},
		befUpload(){
			this.$message({
				type: "error",
				message: "无法上传图片"
			})
			return false
		},
		/**
		 * @desc 删除数据
		 * @param {Object} row 表格行数据
		 */
		delet(row){
			this.$confirm('确认要删除吗？')
				.then(_ => {
					deleteRad(row.id).then(res => {
						if(res.code === 200){
							this.getList()
							return this.$message({
								type: "success",
								message: "删除成功"
							})
						}
						return this.$message({
							type: "error",
							message: "删除失败"
						})
					})
				})
				.catch(_ => {});
		},
		/**
		 * @desc 获取数据
		 */
		async getList() {
			this.listLoading = true;
			const { data } = await getSourceList(this.listQuery);
			this.total = data.total;
			this.tableData = data.patrolList;
			this.listLoading = false;
		},
		/**
		 * @desc 编辑查看表格数据
		 * @param {Object} row 表格行数据
		 */
		async handleEdit(row) {
			this.$refs.formDelg.openDialog()
			// this.dialogFormVisible = true;
			this.id = row.id
			// getRadInfo(this.id).then(res => {
			// 	this.handleInfo(res.data)
			// })
			const { data } = await getRadInfo({ id: row.id });
			// this.editInfo = data.data;
			this.fileList = [];
			// data.data.file = 'http://a1.att.hudong.com/05/00/01300000194285122188000535877.jpg'
			if(data.data.file){
				this.fileList.push({
					name: data.data.file.split('/').pop(),
					url: data.data.file
				})
			}
			delete data.data.file;
			const parent = this.$refs.formDelg.getFormEle().forEach(item => {
				item[0].setDefaultValue(data.data);
				this.changeSource('place', data.data.place)
				this.changeSource('useSourceDevice', data.data.useSourceDevice)
			});
			this.dialogFormVisible = true;
		},
		/**
		 * @desc 关闭弹窗回调
		 */
		closeDialog() {
			this.id = ""
		},
		/**
		 * @desc 处理表单数据
		 * @param {Object} formData 表单数据
		 */
		formateForm(formData){
			const result = cloneDeep(formData)
			result.receiptDate = moment(result.receiptDate).format('YYYY-MM-DD')
			result.factoryTime = moment(result.factoryTime).format('YYYY-MM-DD')
			result.entId = this.entData.id;
			return result
		},
		/**
		 * @desc 初始化表单数据
		 * @param {Object} val 表单数据
		 */
		initShowDetail(val) {
			if (val) {
				const parent = this.$refs.formDelg
					.getFormEle()
					.forEach(item => {
						item[0].setDefaultValue(val);
					});
			}
		},
		/**
		 * @desc 新增、编辑数据
		 * @param {Object} formData 表单数据
		 */
		submitForm(val, file) {
			console.log(val);

			// debugger
			if(file){
				val.file = file
			}else{
				if(this.fileList.length === 0 && this.isRemove){
					val.file = 'delete'
				}
			}
			if(this.id) {
				const params = this.formateForm(val)
				updateRad({id: this.id, ...params}).then(res => {
					this.fresh()
					if(res.code === 200){
						this.dialogFormVisible = false;
						this.fileList = [];
						return this.$message({
							type: "success",
							message: "修改成功"
						})
					}
					return this.$message({
						type: "error",
						message: "修改失败"
					})
				})
			} else {
				const params = this.formateForm(val)
				insertRad(params).then(res => {
					this.fresh()
					if(res.code === 200){
						this.dialogFormVisible = false;
						this.fileList = [];
						return this.$message({
							type: "success",
							message: "添加成功"
						})
					}
					return this.$message({
						type: "error",
						message: "添加失败"
					})
				})
			}
		},
		/**
		 * @desc 新增、编辑数据
		 * @param {Object} formData 表单数据
		 */
		submit(value){
			this.$refs.uploadFile.submit()
			this.fileUpload?.then(
				file => {
					this.submitForm(value, file)
				}
			) || this.submitForm(value)
			this.fileUpload = null;
		},
		handleRemove(file, fileList) {
			// debugger
			if(file.status === 'success'){
				let index = this.fileList.findIndex(item => item.url === file.name)
				this.fileList.splice(index, 1)
				this.isRemove = true;
			}
			// console.log(file, fileList);
		},
		handlePictureCardPreview(file) {
			this.dialogImageUrl = file.url;
			this.dialogVisible = true;
		},
		handleInfo(infoObject) { // 处理获取实例信息，与formList的数据的匹配
			if(!infoObject || (typeof infoObject != 'object')) return
			for(let key in infoObject) {
				this.formList.forEach(item => {
					if(key === item.moduleKey) {
						item[key] = infoObject[key]
					}
				})
			}
		},
		changeSource(keys, value){
			if( keys === 'place'){
				const newForm = cloneDeep(this.formList)
				newForm[0].list[1] = {
					type: "select",
					label: "用源设备",
					labelWidth: "180px",
					width: "49.8%",
					placeholder: "",
					moduleKey: "useSourceDevice",
					children: "option",
					options: [
					],
					query: {
						id: value ? value : this.entData.id,
						type: value ? 'site' : 'enterprise',
					},
					fetch:getDeviceInfo,
					validate: function() {
						return [
							{required: false, message: '请选择用源设备', trigger: "blur"}
						]
					}
				}
				this.formList = newForm
			}
			if( keys === 'useSourceDevice' ){
				const newForm = cloneDeep(this.formList)
				newForm[0].list[5] = {
					type: "select",
					label: "源用途",
					labelWidth: "180px",
					width: "50%",
					placeholder: "",
					moduleKey: "sourceUse",
					fetchTimes: Infinity,
					children: "option",
					options: [
					],
					query: {
						id: value,
					},
					fetch:getRadUsedInfo,
					validate: function() {
						return [
							{required: false, message: '请选择源用途', trigger: "blur"}
						]
					}
				}
				this.formList = newForm
				setTimeout(() => {
					this.$refs.formDelg.getFormEle().forEach(item => {
						item[0].getFormList('sourceUse').then(res => {
							item[0].setDefaultValue({sourceUse: res[0].value});
						})
					});
				}, 100)
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.archives_sourceinfo_info {
	/deep/ .el-upload.el-upload--picture-card{
		display: block;
	}
}
.archives_sourceinfo_info.noCard{
	/deep/ .el-upload.el-upload--picture-card{
		display: none;
	}
}
</style>
